package com.security.config;

import com.alibaba.fastjson.JSON;
import com.common.response.ResponseBean;
import com.common.response.ResponseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;

/**
* @Description:  认证失败处理类，返回401
* @Author: zyj
* @Date: 2020/1/3
*/
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);

    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        //验证为未登陆状态会进入此方法，认证错误
        logger.error("认证失败:", authException);
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        ResponseBean responseBean = new ResponseBean();
        responseBean.setCode(ResponseCode.UNAUTHORIZED.getValue());
        responseBean.setMessage(ResponseCode.UNAUTHORIZED.getDescripe());
        printWriter.write(JSON.toJSONString(responseBean));
        printWriter.flush();
    }
}
